package com.sysd.mail.smtp.command;

import com.sysd.mail.smtp.SmtpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * project: mail
 *
 * @author bsh
 * @description BaseSmtpSession
 * @dataTime 2023/3/27 17:06
 * @company 丽水信阳软件科技有限公司
 */
abstract public class BaseSmtpCommand implements SmtpCommand {
    private final String command;

    public BaseSmtpCommand(String command) {
        this.command = command;
    }

    /**
     * 执行命令
     *
     * @param command     命令名称
     * @param smtpSession smtp session
     * @return smtp session
     * @throws IOException io exception
     */
    @Override
    abstract public SmtpSession execute(String command, SmtpSession smtpSession) throws IOException;

    /**
     * 获取命令名称
     *
     * @return 命令名称
     */
    @Override
    public String getCommand() {
        return this.command;
    }

    /**
     * 获取命令名称
     *
     * @param commandString 命令字符串
     * @return 命令
     */
    protected String getCommandName(String commandString) {
        if (commandString == null || commandString.length() < 4) {
            return "";
        }
        return commandString.trim().substring(4);
    }

    /**
     * 获取命令和参数
     *
     * @param commandString 字符串
     * @return 命令和字符串
     */
    protected String[] getCommandNameAndArgs(String commandString) {
        List<String> list = new ArrayList<>();
        StringTokenizer stringTokenizer = new StringTokenizer(commandString);
        while (stringTokenizer.hasMoreTokens()) {
            list.add(stringTokenizer.nextToken());
        }
        return list.toArray(new String[0]);
    }
}
